package com.frkj.yuan.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.frkj.yuan.R;
import com.frkj.yuan.api.bean.HospitalPoiListBean;
import com.frkj.yuan.api.bean.NearPeizhenPerson;
import com.frkj.yuan.api.bean.OrderDetialsBean;
import com.frkj.yuan.api.category.HospitalPoiCategory;
import com.frkj.yuan.api.presenter.HospitalPoiPresenter;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.main.MainActivity;
import com.frkj.yuan.utils.FullScreenUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 信息说明:
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/5/6 15 ：44
 * 项目名称：yuanban
 */
public class WaitOrderMapActivity extends AppCompatActivity implements AMap.OnMapLoadedListener, AMap.OnMapClickListener, LocationSource, AMapLocationListener, HospitalPoiCategory.View, View.OnClickListener, AMap.OnInfoWindowClickListener {
    private AMap aMap;
    private MapView mapView;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private OnLocationChangedListener mListener;
    private Marker locMarker;
    private Circle ac;
    private Circle c;
    private long start;
    private final Interpolator interpolator1 = new LinearInterpolator();
    private TimerTask mTimerTask;
    private Timer mTimer = new Timer();
    private HospitalPoiPresenter mPresenter;
    private long hospitalId;
    private String hospitalName;
    private TextView address_yiyuan;
    private CameraUpdate mUpdata;
    private MarkerOptions markerOption;
    private Marker marker;
    private String mToken;
    private String orderId;
    private Timer time;
    private TimerTask timerTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_map_view);
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        init();
        FullScreenUtils.getInstance().fullScreen(WaitOrderMapActivity.this, true);
        /*
         * 设置离线地图存储目录，在下载离线地图或初始化地图设置;
         * 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
         * 则需要在离线地图下载和使用地图页面都进行路径设置
         * */
        //Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
        // MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
        hospitalId = getIntent().getLongExtra("hospitalId", 0);
        orderId = getIntent().getStringExtra("orderId");
        hospitalName = getIntent().getStringExtra("hospitalName");
        address_yiyuan = (TextView) findViewById(R.id.address_yiyuan);
        address_yiyuan.setText(hospitalName);
        findViewById(R.id.base_back_dingwei).setOnClickListener(this);
        mToken = (String) SPUtils.get(WaitOrderMapActivity.this, ConstantStaticUrl.mToken, "");
        mPresenter = new HospitalPoiPresenter(this);
        SetPersenter(mPresenter);
        mPresenter.getHospitalPoiList(hospitalId);
        time=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
                mPresenter.getOrderDeials(mToken, orderId);
            }
        };
        time.scheduleAtFixedRate(timerTask,5000,5000); //延时1000ms后开始，每100ms一次
    }
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setOnMapLoadedListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setLogoBottomMargin(-50);//隐藏logo
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(WaitOrderMapActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        mPresenter.getHospitalPoiList(hospitalId);
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        deactivate();
        timerTask.cancel();
    }

    @Override
    public void onMapLoaded() {
    }
    @Override
    public void onMapClick(LatLng latLng) {
    }
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        startlocation();
    }
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }
    /**
     * 开始定位。
     */
    private void startlocation() {
        if (mLocationClient == null) {
            try {
                mLocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mLocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置为单次定位
            mLocationOption.setOnceLocation(true);
            // 设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        } else {
            mLocationClient.startLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (mTimerTask != null) {
                mTimerTask.cancel();
                mTimerTask = null;
            }
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                LatLng mylocation = new LatLng(aMapLocation.getLatitude(),
                        aMapLocation.getLongitude());
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 19));
//                addLocationMarker(aMapLocation);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": "
                        + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void addLocationMarker(LatLng latLng) {
        if (locMarker == null) {
//            locMarker = addMarker(latLng);
            ac = aMap.addCircle(new CircleOptions().center(latLng)
                    .fillColor(Color.argb(100, 255, 218, 185)).radius(90.0)
                    .strokeColor(Color.argb(255, 255, 228, 185)).strokeWidth(5));
            c = aMap.addCircle(new CircleOptions().center(latLng)
                    .fillColor(Color.argb(70, 255, 218, 185))
                    .radius(90.0).strokeColor(Color.argb(255, 255, 228, 185))
                    .strokeWidth(0));
        } else {
            locMarker.setPosition(latLng);
            ac.setCenter(latLng);
            ac.setRadius(90.0);
            c.setCenter(latLng);
            c.setRadius(90.0);
        }
        Scalecircle(c);
    }


    public void Scalecircle(final Circle circle) {
        start = SystemClock.uptimeMillis();
        mTimerTask = new circleTask(circle, 1000);
        mTimer.schedule(mTimerTask, 0, 5);
    }

    @Override
    public void getOrderDeials(OrderDetialsBean order) {
        if (order.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (order.getData() != null) {
                if (order.getData().isAlreadyReceiving() == true) {
                    Intent intent = new Intent(WaitOrderMapActivity.this, YuyueSuccessAcitivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                    finish();
                }
            }
        }
    }

    @Override
    public void getHospitalPoiList(HospitalPoiListBean hospital) {
        if (hospital.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (hospital.getData() != null) {
                LatLng latLng = new LatLng(Double.parseDouble(hospital.getData().getLatitude()), Double.parseDouble(hospital.getData().getLongitude()));
                mUpdata = CameraUpdateFactory.newCameraPosition(
                        //15是缩放比例，0是倾斜度，30显示比例
                        new CameraPosition(latLng, 17, 0, 30));//这是地理位置，就是经纬度。
                aMap.moveCamera(mUpdata);//定位的方法
                markerOption = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.red_nav_bg))
                        .position(latLng)
                        .title("正在为您搜索 优质陪诊人员")
                        .draggable(true);
                marker = aMap.addMarker(markerOption);
                marker.showInfoWindow();
                // marker旋转90度
                marker.setRotateAngle(0);
                addLocationMarker(latLng);
                mPresenter.getNearPeizhen(hospital.getData().getLatitude(), hospital.getData().getLongitude());
            } else {
                ToastUtil.showToastINFO(WaitOrderMapActivity.this, hospital.getMsg());
            }
        }
    }
    @Override
    public void getNearPeizhen(NearPeizhenPerson person) {
        if (person.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (person.getData() != null && person.getData().size() > 0) {
                for (NearPeizhenPerson.NearPeizhenPersonData near : person.getData()) {
                    for (int i = 0; i < near.getPzvos().size(); i++) {
                        LatLng latlng = new LatLng(Double.parseDouble(near.getPzvos().get(i).getLatitude()), Double.parseDouble(near.getPzvos().get(i).getLongitude()));
                        addMarkersToMap(latlng);// 往地图上添加marker
                    }
                }
            }
        }

    }

    private void addMarkersToMap(LatLng latlng) {
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pzy_nav_bg))
                .position(latlng)
                .draggable(true);
        marker = aMap.addMarker(markerOption);
        marker.showInfoWindow();
        // marker旋转90度
        marker.setRotateAngle(0);
    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastINFO(WaitOrderMapActivity.this, mErrorMsg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_back_dingwei:
                Intent intent = new Intent(WaitOrderMapActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                break;
        }
    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }


    private class circleTask extends TimerTask {
        private double r;
        private Circle circle;
        private long duration = 1000;

        public circleTask(Circle circle, long rate) {
            this.circle = circle;
            this.r = circle.getRadius();
            if (rate > 0) {
                this.duration = rate;
            }
        }

        @Override
        public void run() {
            try {
                long elapsed = SystemClock.uptimeMillis() - start;
                float input = (float) elapsed / duration;
//                外圈循环缩放
//                float t = interpolator.getInterpolation((float)(input-0.25));//return (float)(Math.sin(2 * mCycles * Math.PI * input))
//                double r1 = (t + 2) * r;
//                外圈放大后消失
                float t = interpolator1.getInterpolation(input);
                double r1 = (t + 1) * r;
                circle.setRadius(r1);
                if (input > 2) {
                    start = SystemClock.uptimeMillis();
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}
